
//
//  BYJMVViewController.m
//  BLDMusics
//
//  Created by 白云杰 on 16/3/19.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "BYJMVViewController.h"

@interface BYJMVViewController ()<UITableViewDataSource, UITableViewDelegate, NSURLSessionDownloadDelegate>

/** 播放器 */
@property (nonatomic, retain) UIView *MVView;
/** MVTableView */
@property (nonatomic, retain) UITableView *MVTableView;
/** 接收数据 */
@property (nonatomic, retain) NSArray *dataSource;
/** 解析的网址 */
@property (nonatomic, retain) NSString *url;
/**< 播放器对象 */
@property (nonatomic, retain) AVPlayer *player;
/**< 播放项目 */
@property (nonatomic, retain) AVPlayerItem *playerItem;
 /**< 用于显示播放器 */
@property (nonatomic, retain) AVPlayerLayer *playerLayer;
/** 记录播放状态 */
@property (nonatomic, assign) BOOL playAndPause;
/** 记录播放器上的控制条 */
@property (nonatomic, assign) BOOL isAlpha;
/** 声音 */
@property (nonatomic, assign) CGFloat totalDuration;
/** 显示播放器下面条 */
@property (retain, nonatomic) UIView *bottomView;
/** 开始播放 */
@property (retain, nonatomic) UIButton *playerButton;
/** 全屏 */
@property (nonatomic, retain) UIButton *screenButton;
/** 进度条 */
@property (retain, nonatomic) UISlider *progressSlider;
/** 显示时间的label */
@property (retain, nonatomic) UILabel *timeLabel;
/** 下载 */
@property (nonatomic,strong) NSURLSession *session;
/** 返回按钮 */
@property (nonatomic, retain) UIButton *returnButton;
/** 下载进度条 */
@property (nonatomic, retain) UIProgressView *progressV;

@end

@implementation BYJMVViewController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    [PlayViewController sharePlayViewBar].hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    [self.player pause];
    [PlayViewController sharePlayViewBar].hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    [self dataHandle];
    [self createControl];
    [self createTableView];
}

- (void)createControl {
    
    self.MVView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 2 / 3)];
    _MVView.backgroundColor = [UIColor blackColor];
    _MVView.userInteractionEnabled = YES;
    [self.view addSubview:_MVView];
    
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH * 2 / 3 - 50, SCREEN_WIDTH, 50)];
    _bottomView.backgroundColor = [UIColor clearColor];
    [_MVView addSubview:_bottomView];
    
    self.playerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playerButton.frame = CGRectMake(5, 5, 40, 40);
    _playerButton.backgroundColor = [UIColor clearColor];
    [_playerButton setImage:[UIImage imageNamed:@"icon_pause"] forState:UIControlStateNormal];
    [_playerButton addTarget:self action:@selector(playerButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_playerButton];
    
    self.screenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _screenButton.frame = CGRectMake(SCREEN_WIDTH - 45, 5, 40, 40);
    _screenButton.backgroundColor = [UIColor clearColor];
    [_screenButton setImage:[UIImage imageNamed:@"iconfont-quanping-2"] forState:UIControlStateNormal];
    [_screenButton addTarget:self action:@selector(screenButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_screenButton];
    
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(50, 10, SCREEN_WIDTH - 100, 20)];
    _progressSlider.backgroundColor = [UIColor clearColor];
    [_progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventValueChanged];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"dot_selected"] forState:UIControlStateNormal];
    [_bottomView addSubview:_progressSlider];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 30, SCREEN_WIDTH / 2, 20)];
    _timeLabel.backgroundColor = [UIColor clearColor];
    [_bottomView addSubview:_timeLabel];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.text = @"3333333";
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.MVView addGestureRecognizer:tap];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    
    
    // 添加播放器
    [self addAVPlayer];
    // 添加进度监听
    [self addProgressObserver];
    
    [self addNotifiactionCenter];
    
    [self.player play];
    //    [self.player pause];
    // 赋初值 提升用户体验
    self.progressSlider.value = 0;
    self.timeLabel.text = @"--:--/--:--";
    
    _playAndPause = YES;
    _isAlpha = YES;
    
    [UIView animateWithDuration:0.05 animations:^{
        self.bottomView.alpha = 0;
    }];
    
    self.returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _returnButton.frame = CGRectMake(20, 20, 30, 30);
    _returnButton.backgroundColor = [UIColor clearColor];
    [_returnButton addTarget:self action:@selector(returnButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_returnButton setImage:[UIImage imageNamed:@"item"] forState:UIControlStateNormal];
    [self.view addSubview:_returnButton];
    
}

#pragma mark - 通知方法
- (void)addNotifiactionCenter {
    
    // 添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChanged:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

// 当屏幕方向发生变化的时候会执行
- (void)statusBarOrientationChanged:(NSNotification *)notification {
    
    // 获取到当前屏幕旋转的方向
    UIInterfaceOrientation orientatiton = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientatiton == UIInterfaceOrientationLandscapeLeft) {
        //NSLog(@"向左横屏");
        [self setplayerFrame];
    }
    if (orientatiton == UIInterfaceOrientationLandscapeRight) {
        //NSLog(@"向右横屏");
        [self setplayerFrame];
    }
    if (orientatiton == UIInterfaceOrientationPortrait) {
        //NSLog(@"竖屏");
        [self setplayerFrame];
    }
}

- (void)setplayerFrame {
    
    self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.MVView.frame.size.height);
}

/** 添加播放器 */
- (void)addAVPlayer {
    
    NSString *str = _model.url;
    
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:str];
    
    // 创建播放项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    // 创建播放器对象
    self.player = [[AVPlayer alloc] initWithPlayerItem:_playerItem];
    // 创建承载播放器的layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.MVView.frame.size.height);
    // 设置视频 填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    // 讲播放器放到playerView上
    [self.MVView.layer insertSublayer:self.playerLayer atIndex:0];
    
    
    
}

#pragma mark - 播放进度监听
/** 播放进度监听 */
- (void)addProgressObserver {
    
    // CMTime 是专门计算视频的时间格式
    // Core Media
    // 参数1：设置监听的时间间隔
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 你监听我干嘛
        // 获取到总的视频时间
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        // 获取到当前时间
        CGFloat current = CMTimeGetSeconds(self.playerItem.currentTime);
        
        // 把总时间转化为字符串显示再label上
        NSString *durationT = [NSString stringWithFormat:@"%02d:%02d", (int)duration / 60, (int)duration % 60];
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];
        // 拼接字符串显示在label上
        NSString *timetr = [NSString stringWithFormat:@"%@ %@", currentT, durationT];
        self.timeLabel.text = timetr;
        
        // 记录总时间，slider需要使用
        self.totalDuration = duration;
        
        // slider的value
        self.progressSlider.value = current / duration;
        
        
        
    }];
}


- (void)returnButtonAction:(UIButton *)button {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)playerButtonAction:(UIButton *)button {
    if (_playAndPause == YES) {
        [self.player pause];
        [_playerButton setImage:[UIImage imageNamed:@"icon_play"] forState:UIControlStateNormal];
    } else {
        [self.player play];
        [_playerButton setImage:[UIImage imageNamed:@"icon_pause"] forState:UIControlStateNormal];
    }
    
    _playAndPause = !_playAndPause;
}

- (void)screenButtonAction:(UIButton *)button {
 
    // UIDevice指标
    // UIDeviceOrientation      是机器硬件的当前旋转方向   这个你只能取值 不能设置
    // UIInterfaceOrientation   是你程序界面的当前旋转方向   这个可以设置
    // 当前设备的旋转方向 不是竖屏(也就是横屏的时候)让他竖屏 相反 则为横屏
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        
        _MVTableView.hidden = NO;
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        
        self.MVView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH * 2 / 3);
        
        self.bottomView.frame = CGRectMake(0, SCREEN_WIDTH * 2 / 3 - 50, SCREEN_WIDTH, 50);
        
        self.playerButton.frame = CGRectMake(5, 5, 40, 40);
        
        self.screenButton.frame = CGRectMake(SCREEN_WIDTH - 45, 5, 40, 40);
        
        self.progressSlider.frame = CGRectMake(50, 10, SCREEN_WIDTH - 100, 20);
        
        self.timeLabel.frame = CGRectMake(50, 30, SCREEN_WIDTH / 2, 20);
        
        self.returnButton.hidden = NO;
        
    } else {
        
        _MVTableView.hidden = YES;
        
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        
        self.MVView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGTH);
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGTH - 50, SCREEN_WIDTH, 50);
        self.screenButton.frame = CGRectMake(SCREEN_WIDTH - 45, 5, 40, 40);
        self.playerLayer.frame = _MVView.bounds;
        self.progressSlider.frame = CGRectMake(50, 10, SCREEN_WIDTH - 100, 20);
        self.timeLabel.frame = CGRectMake(50, 30, SCREEN_WIDTH / 2, 20);
        _playerButton.frame = CGRectMake(5, 5, 40, 40);
        
        self.returnButton.hidden = YES;
    }

}

- (void)progressSliderAction:(UISlider *)slider1 {
    // 获取到UISloder对象
    UISlider *slider = slider1;
    
    // 获取到当前进度时间
    CGFloat currentTime = self.totalDuration * slider.value;
    // 转化为CMTime
    CMTime dragTime = CMTimeMake(currentTime, 1);
    
    [self.player seekToTime:dragTime completionHandler:^(BOOL finished) {
        // 到了时间之后 开始播放
        [self.player play];
    }];

}

// 手势的方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (_isAlpha == NO) {
        [UIView animateWithDuration:0.05 animations:^{
            self.bottomView.alpha = 0;
        }];
    } else {
        [UIView animateWithDuration:0.05 animations:^{
            self.bottomView.alpha = 0.8;
        }];
    }
    _isAlpha = !_isAlpha;
}


- (void)createTableView {
    
    self.MVTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH * 2 / 3, SCREEN_WIDTH, SCREEN_HEIGTH - SCREEN_WIDTH * 2 / 3) style:UITableViewStylePlain];
    _MVTableView.delegate = self;
    _MVTableView.dataSource = self;
    [self.view addSubview:_MVTableView];
    
    [_MVTableView registerClass:[BYJMVTableViewCell class] forCellReuseIdentifier:@"BYJMVTableViewCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
    
    BYJView *likesView = [[BYJView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 8 - 25, 0, 50, 50)];
    [view addSubview:likesView];
    [likesView.BYJButton addTarget:self action:@selector(likesButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [likesView.BYJButton setImage:[[UIImage imageNamed:@"face_3"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    BYJView *commentView = [[BYJView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 3 / 8 - 25, 0, 50, 50)];
    
    [view addSubview:commentView];
    [commentView.BYJButton addTarget:self action:@selector(commentButton:) forControlEvents:UIControlEventTouchUpInside];
    [commentView.BYJButton setImage:[UIImage imageNamed:@"face_4"] forState:UIControlStateNormal];
  
    BYJView *shareView = [[BYJView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 5 / 8 - 25, 0, 50, 50)];
    [view addSubview:shareView];
    [shareView.BYJButton addTarget:self action:@selector(shareButton:) forControlEvents:UIControlEventTouchUpInside];
    [shareView.BYJButton setImage:[UIImage imageNamed:@"list_menu_share"] forState:UIControlStateNormal];
    shareView.BYJLabel.font = [UIFont systemFontOfSize:15];
    shareView.BYJLabel.text = @"分享";
    
    BYJView *downloadView = [[BYJView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 7 / 8 - 25, 0, 50, 50)];
    [view addSubview:downloadView];
    [downloadView.BYJButton addTarget:self action:@selector(downloadButton:) forControlEvents:UIControlEventTouchUpInside];
    [downloadView.BYJButton setImage:[UIImage imageNamed:@"list_menu_download"] forState:UIControlStateNormal];
    downloadView.BYJLabel.font = [UIFont systemFontOfSize:15];
    downloadView.BYJLabel.text= @"下载";
    
    self.progressV = [[UIProgressView alloc] initWithProgressViewStyle:(UIProgressViewStyleBar)];
    //    _progressV.frame =  CGRectMake(10,  SCREEN_HEIGTH - 10, SCREEN_WIDTH - 20, 40);
    _progressV.frame = CGRectMake(50, 30, SCREEN_WIDTH - 100, 20);
    
    // 改变默认高度
    _progressV.transform = CGAffineTransformMakeScale(1.0f, 3.0f);
    _progressV.backgroundColor = [UIColor clearColor];
    _progressV.progressImage = [UIImage imageNamed:@"2222.jpg"];
    _progressV.trackTintColor = [UIColor clearColor];
    [view addSubview:_progressV];
    
    return view;
}

- (void)likesButtonAction:(UIButton *)button {
    
}

- (void)commentButton:(UIButton *)button {
    
}

- (void)shareButton:(UIButton *)button {
}

- (void)downloadButton:(UIButton *)button {
    
    [self downloadFile2];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BYJMVTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BYJMVTableViewCell" forIndexPath:indexPath];
    BYJMVModel *model = _dataSource[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BYJMVViewController *VC = [[BYJMVViewController alloc] init];
    BYJMVModel *model = _dataSource[indexPath.row];
    BYJmvListModel *model1 = model.mvListArr[0];
    VC.model = model1;
    //VC.videoId = model.videoId;
    
//    [self.navigationController pushViewController:VC animated:YES];
    [self presentViewController:VC animated:YES completion:^{
        
    }];
}

- (void)dataHandle {
    
    self.url = [NSString stringWithFormat:@"http://api.dongting.com/sim/mv/%@/similarity", _model.videoId];
    
    [APPTools GETWithURL:_url par:nil success:^(id responseObject) {
        self.dataSource = [BYJMVModel modelHandleWithArray:responseObject[@"data"]];
        [_MVTableView reloadData];
    } filed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

/**
 *  使用代理监控下载进度
 */
- (void)downloadFile2
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_model.url] cachePolicy:1 timeoutInterval:15];
    [[self.session downloadTaskWithRequest:request]resume];
}

#pragma mark - 代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSString *pathFile = [NSTemporaryDirectory() stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSFileManager *manger = [NSFileManager defaultManager];
    [manger copyItemAtPath:location.path toPath:pathFile error:NULL];
    
    NSLog(@"%@", pathFile);
}

// 进度数据
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
    _progressV.progress = progress;
    
    if (progress == 1) {
        _progressV.hidden = YES;
    }
}

// 懒加载
- (NSURLSession *)session
{
    if(_session == nil)
    {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
